package com.kunyi.web.service.identity.db.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kunyi.web.service.identity.db.entity.domain.LeafAlloc;
import com.kunyi.web.service.identity.db.mapper.LeafAllocMapper;
import com.kunyi.web.service.identity.db.service.ILeftAllocService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * @ClassName ILeftAllocServiceImpl
 * @Description TODO
 * @Author zhenguo.zhuang
 * @Date 2024/7/5 17:23
 * @Version 1.0
 */
@Slf4j
@Service
public class ILeftAllocServiceImpl extends ServiceImpl<LeafAllocMapper, LeafAlloc> implements ILeftAllocService {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    private final SqlSessionFactory sqlSessionFactory;

    public ILeftAllocServiceImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public List<LeafAlloc> getAllLeafAllocs() {
        return baseMapper.getAllLeafAllocs();
    }
    @Override
    public  LeafAlloc updateMaxIdAndGetLeafAlloc(String tag) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(); // 开启手动提交模式的session
        try {
            LeafAllocMapper mapper = session.getMapper(LeafAllocMapper.class);
            mapper.updateMaxId(tag);
            LeafAlloc leafAlloc = mapper.getLeafAlloc(tag);
            session.commit();
            return leafAlloc;
        } catch (Exception e) {
            // 若出现异常，则回滚事务
            session.rollback();
            // 处理异常
            throw e;
        } finally {
            // 在finally块中确保释放SqlSession资源
            if (session != null) {
                session.close();
            }
        }


    }
    @Override
    public  LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(); // 开启手动提交模式的session
        try {
            LeafAllocMapper mapper = session.getMapper(LeafAllocMapper.class);
            mapper.updateMaxIdByCustomStep(leafAlloc);
            LeafAlloc leafAlloc1 = mapper.getLeafAlloc(leafAlloc.getBizTag());
            session.commit();
            return leafAlloc1;
        } catch (Exception e) {
            // 若出现异常，则回滚事务
            session.rollback();
            // 处理异常
            throw e;
        } finally {
            // 在finally块中确保释放SqlSession资源
            if (session != null) {
                session.close();
            }
        }


    }

    @Override
    public List<String> getAllTags() {
        return baseMapper.getAllTags();
    }
}
